package vip.zslaa.mongodb.controller;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;
import vip.zslaa.mongodb.entity.User;

import java.util.Date;
import java.util.List;

/**
 * @author ：zslaa
 * @date ：Created in 9/7/2019 11:34 PM
 * @description：
 * @version: $
 */
@RestController
public class UserController {
    @Autowired
    private MongoTemplate mongoTemplate;
//    表面
    private static final String collectionName = "user";
//    添加user
    @RequestMapping(value = "insert" ,method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String insert(){
        User user = new User();
        user.setUsername("张三");
        user.setPassword("1111111");
        user.setBirthday(new Date());
        user.setHeight(120);
        this.mongoTemplate.insert(user);
        return "ok";
    }
//    删除
    @RequestMapping(value = "delete" ,method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Long delete(@RequestParam("id") String id){
        Query query = Query.query(Criteria.where("_id").is(id));
        DeleteResult remove = this.mongoTemplate.remove(query, collectionName);
        return remove.getDeletedCount();
    }

//    更新
    @RequestMapping(value = "update",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Long update(@ModelAttribute User user){
        System.out.println(user.toString());
        Query query = Query.query(Criteria.where("_id").is(user.getId()));
        Update update = new Update();
        update.set("username",user.getUsername());
        update.set("password",user.getPassword());
        update.set("height",user.getHeight());
        update.set("birthday",user.getBirthday());
        UpdateResult updateResult = this.mongoTemplate.updateFirst(query, update, collectionName);
        return updateResult.getMatchedCount();
    }

//    查询
    @RequestMapping(value = "query",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public List<User> query(){
        Query query = Query.query(Criteria.where("username").is("zslaa"));
        List<User> users = this.mongoTemplate.find(query, User.class);
        return users;
    }


}
